<template>
  <div class="login_container common_drag">
    <div class="fff left_top common_no_drag">
      <img
        class="cur_poi"
        @click="handleMinimize"
        src="../assets/head_imgs/head_reduce.png"
        alt=""
      />
      <img
        class="cur_poi"
        @click="handleClose"
        src="../assets/close_head.png"
        alt=""
      />
    </div>
    <div class="logo fff flex">
      <img src="../assets/logo.png" alt="" />
      <div>
        <div class="title">欣心</div>
        <div class="title">寻找不一样的你</div>
      </div>
    </div>
    <div class="left common_no_drag">
      <div
        class="btn flex cur_poi"
        :class="{ active_btn: currLoginType === 1 }"
        @click="loginStatus(1)"
      >
        <img src="../assets/video_ico.png" alt="" />
        <span class="fff">主播</span>
      </div>
      <div
        class="btn flex cur_poi"
        :class="{ active_btn: currLoginType === 2 }"
        @click="loginStatus(2)"
      >
        <img src="../assets/auto_ico.png" alt="" />
        <span class="fff">主持</span>
      </div>
    </div>
    <div class="right flex_colm flex">
      <div class="title">欢迎您，主播~</div>
      <el-form
        class="common_no_drag"
        ref="ruleFormRef"
        :rules="ruleLogin"
        :model="formLogin"
        label-width="auto"
        style="max-width: 600px"
      >
        <div class="inp_form row_inp">
          <el-form-item prop="phone">
            <el-input
              placeholder="请输入手机号"
              v-model.trim="formLogin.phone"
            />
          </el-form-item>
        </div>
        <div class="inp_form2 inp_form fff row_inp">
          <el-form-item prop="verifyCode">
            <el-input
              placeholder="请输入验证码"
              v-model.trim="formLogin.verifyCode"
            />
          </el-form-item>
          <el-button
            :disabled="true"
            style="flex: 1; margin-left: 15px; background: #32343a"
            class="fff"
            v-if="second > 1"
            >{{ second }}s</el-button
          >
          <el-button v-else class="btn_verify fff" @click="handlerVerifyCode"
            >获取验证码</el-button
          >
        </div>

        <div class="record fff">
          <el-form-item>
            <el-checkbox :value="formLogin.deleteDate" name="type">
              5天内自动登录
            </el-checkbox>
          </el-form-item>
        </div>
        <div class="read_http fff">
          <el-form-item prop="checkHttp">
            <el-checkbox
              class="custom-checkbox fs_11"
              label=""
              :value="formLogin.checkHttp"
            >
              我已阅读并同意欣心
            </el-checkbox>
            <span class="fs_11 cur_poi" @click="handleAgreement"
              >《用户注册协议》</span
            >
            和<span class="fs_11 cur_poi" @click="handlePolicy"
              >《隐私政策》</span
            >
          </el-form-item>
        </div>
      </el-form>

      <div
        @click="linkToHome"
        class="cur_poi common_no_drag btn_log inp_form flex fff"
      >
        登录
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { smsApi, loginApi, $TipMessage } from "../http";
import { useCounterStore } from "../store";
const jsonVal = require("jsonwebtoken");
const store = useCounterStore();
const key = "xinxin-1.0.1";
const allowedAlgs = ["HS256"];
const { ipcRenderer } = require("electron");
const second = ref(-1);
const profile = ref(null);
let timer = null;
const formLogin = ref({
  phone: "",
  verifyCode: "",
  deleteDate: "",
  checkHttp: "",
});
const currLoginType = ref(1);
//
const ruleFormRef = ref(null);
const validatePhone = (rule, val, callback) => {
  if (!val) {
    return callback(new Error("请输入手机号"));
  }
  function isPhone(phone) {
    const regex = /^1[3-9]\d{9}$/;
    return regex.test(phone);
  }
  if (!isPhone(val)) {
    return callback(new Error("请输入正确的手机号"));
  }
  return callback();
};
const validateVerifyCode = (rule, val, callback) => {
  if (!val) {
    return callback(new Error("请输入验证码"));
  }
  return callback();
};
const validateCheckHttp = (rule, val, callback) => {
  console.log("协议-val", val);
  if (!val) {
    return callback(new Error("请勾选协议"));
  }
  return callback();
};
const ruleLogin = reactive({
  phone: [{ validator: validatePhone, trigger: "blur" }],
  verifyCode: [{ validator: validateVerifyCode, trigger: "blur" }],
  // checkHttp: [{ validator: validateCheckHttp, trigger: "blur" }],
});

const handleMinimize = () => {
  ipcRenderer.send("login_minimize");
};
const handleClose = () => {
  ipcRenderer.send("windows_close");
};
const loginStatus = (cur) => {
  currLoginType.value = cur;
};
const handlerVerifyCode = () => {
  console.log("ruleFormRef.value", ruleFormRef.value);
  ruleFormRef.value.validateField("phone", (v) => {
    console.log("phone", v);
    if (v) {
      smsApi(formLogin.value.phone).then((res) => {
        console.log("http-res", res);
        if (res.data.errcode === 0) {
          $TipMessage(res.data.data.res, "success");
          second.value = 60;
          timer = setInterval(() => {
            second.value -= 1;
            if (second.value <= 1) {
              clearTimeout(timer);
            }
          }, 1000);
        } else {
          $TipMessage(res.data.errmsg, "success");
        }
      });
    }
  });
};

const decodeJWT = (token, key, allowedAlgs) => {
  try {
    const decoded = jsonVal.verify(token, key, { algorithms: allowedAlgs });
    const timestamp = Math.floor(Date.now() / 1000);
    const leeway = 60;
    if (decoded.nbf && decoded.nbf > timestamp + leeway) {
      throw new Error(
        `Cannot handle token prior to ${new Date(
          decoded.nbf * 1000
        ).toISOString()}`
      );
    }

    if (decoded.iat && decoded.iat > timestamp + leeway) {
      throw new Error(
        `Cannot handle token prior to ${new Date(
          decoded.iat * 1000
        ).toISOString()}`
      );
    }

    if (decoded.exp && timestamp - leeway >= decoded.exp) {
      throw new Error("Expired token");
    }

    return decoded;
  } catch (error) {
    throw new Error(`JWT 解码失败: ${error.message}`);
  }
};

const linkToHome = () => {
  // formLogin.value.verifyCode = "1234";
  // formLogin.value.phone = 15321178626;
  ruleFormRef.value
    .validate()
    .then((_) => {
      console.log("login-------", formLogin.value);
      loginApi(formLogin.value.verifyCode, formLogin.value.phone)
        .then((res) => {
          console.log("login res", res);
          if (res.data.errcode === 0) {
            try {
              console.log("debugger");
              profile.value = res.data.data;
              profile.value["deleteDate"] = new Date().getTime();
              store.profile = profile.value;
              localStorage.setItem("profile", JSON.stringify(profile.value));
              let temp = profile.value.jwt;
              const payload = decodeJWT(temp, key, allowedAlgs);
              store.tempOb = payload;
              localStorage.setItem("tempOb", JSON.stringify(payload));
              console.log("store.tempOb", store.tempOb);
              $TipMessage("登录成功", "suceess");
              ipcRenderer.send("login-success");
              router.push("/home");
            } catch (error) {
              console.error(error.message);
            }
          } else {
            $TipMessage(res.data.errmsg, "error");
          }
        })
        .catch((err) => {
          console.log("login err", err);
        });
    })
    .catch((err) => {
      for (const key in err) {
        return $TipMessage(err[key][0].message, "error");
      }
    });
};
onMounted(() => {
  if (localStorage.getItem("profile")) {
    let profile = JSON.parse(localStorage.getItem("profile"));
    let currTim = profile.deleteDate;
    let fiveTim = profile.deleteDate + 5 * 24 * 60 * 60 * 1000;
    console.log("fiveTim", fiveTim);
    if (currTim > fiveTim) {
      localStorage.clear();
    } else {
      ipcRenderer.send("login-success");
      router.push("/home");
    }
  }
});
</script>
<style scoped lang="scss">
.login_container {
  width: 100vw;
  height: 100vh;
  background: #1d2022;
  display: flex;
  .left_top {
    position: absolute;

    right: 15px;
    top: 15px;
    img {
      width: 25px;
      height: 25px;
    }
    img:first-child {
      margin-right: 15px;
    }
  }
  .logo {
    position: fixed;
    left: 24px;
    top: 32px;
    img {
      width: 61px;
      height: 61px;
      margin-right: 10px;
    }
    .title {
      font-family: Microsoft YaHei, Microsoft YaHei;
      font-weight: bold;
      font-size: 24px;
      color: #ffffff;
      text-align: left;
      font-style: normal;
      text-transform: none;
    }
    .title:last-child {
      font-size: 12px;
      color: #c3c3c4;
    }
  }
  .left {
    margin: auto 0;
    padding: 0 67px;
    box-sizing: border-box;

    .btn {
      width: 192px;
      padding: 24px 0;

      background: #343739;
      border-radius: 10px 10px 10px 10px;
      border: 1px solid #343739;
      img {
        width: 32px;
        height: 32px;
        margin-right: 22px;
      }
      span {
        display: inline-block;
        height: 100%;
      }
    }
    .btn:first-child {
      margin-bottom: 49px !important;
    }
    .active_btn {
      border: 1px solid #ff3395;
    }
  }
  .right {
    width: 356px;
    .menu_img {
      position: absolute;
      right: 15px;
      top: 15px;
      img {
        width: 25px;
        height: 25px;
      }
      img:first-child {
        margin-right: 15px;
      }
    }
    :deep(.el-input__wrapper) {
      box-shadow: none;
      padding: 15px;
      box-sizing: border-box;
      background: #32343a;
      border-radius: 50px 50px 50px 50px;
    }
    :deep(.el-input__wrapper:active) {
      box-shadow: none;
      border: none;
    }

    .title {
      margin-bottom: 46px;
      font-family: YS HelloFont BangBangTi, YS HelloFont BangBangTi;
      font-weight: 400;
      font-size: 34px;
      color: #ffffff;
      text-align: left;
      font-style: normal;
      text-transform: none;
    }
    .row_inp {
      margin: auto;
    }
    .inp_form {
      width: 356px;
      margin-bottom: 30px;
      :deep(.el-form-item__error) {
        padding-left: 20px;
        box-sizing: border-box;
      }
    }
    .inp_form2 {
      display: flex;
      justify-content: space-between;
      :deep(.el-button) {
        border: none;
        padding: 30px;
        background: #ff3395;
        border-radius: 50px 50px 50px 50px;
      }
    }
    .btn_log {
      padding: 18.5px 0;
      box-sizing: border-box;
      background: linear-gradient(90deg, #fccf52 0%, #ff418f 100%);
      border-radius: 50px 50px 50px 50px;
    }

    .record,
    .read_http {
      padding: 0 20px;
      box-sizing: border-box;
    }
    .read_http {
      font-family: Microsoft YaHei, Microsoft YaHei;
      font-weight: 400;
      text-align: left;
      font-style: normal;
      text-transform: none;
      :deep(.el-checkbox__inner) {
        border-radius: 50%;
      }
    }
    span {
      color: #ff3395;
    }
  }
}
</style>
